package com.jxm.channel;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @Author: jxm
 * @Description:
 * @Date: 2024-2-7 15:18
 * @Version: 1.0
 */
public class ServerSocketChannelDemo {

    public static final String GREETING = "Hello java nio.\r\n";

    public static void main(String[] args) throws Exception{
        int port = 8888; // default
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        }
        //把字节数组放到缓存区中
        ByteBuffer buffer = ByteBuffer.wrap(GREETING.getBytes());

        ServerSocketChannel ssc = ServerSocketChannel.open();
        //绑定
        ssc.socket().bind(new InetSocketAddress(port));
        //非阻塞模式运行
        ssc.configureBlocking(false);

        while (true) {
            System.out.println("Waiting for connections");
            //监听新的连接
            SocketChannel sc = ssc.accept();
            if (sc == null) { //表示没有链接传入
                System.out.println("null");
                Thread.sleep(2000);
            } else {
                System.out.println("Incoming connection from: " + sc.socket().getRemoteSocketAddress());
                buffer.rewind(); //指针0
                sc.write(buffer);
                sc.close();
            }
        }
    }
}
